//
//  TKYHomePageController.m
//  StationHouseHelper
//
//  Created by apple on 2018/5/4.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYHomePageController.h"
#import "TKYProgressCountController.h"
#import "TKYQualityController.h"
#import "TKYSafetyController.h"
#import "TKYChangeStationHouseController.h"
#import "UIViewController+CWLateralSlide.h"
#import "SDCycleScrollView.h"
#import "TKYTitleView.h"
#import "TKYHomePageHeaderView.h"
#import "WMDragView.h"
#import "TKYBimModelController.h"
#import "PPBadgeView.h"
#import "TKYMessageCenterController.h"
#import "TKYSurveyView.h"
#import "TKYProgressSumCell.h"
#import "TKYTaskSumCell.h"
#import "BRPickerView.h"
#import "TKYProjectInfoModel.h"
#import "TKYMessageListModel.h"
#define kProgressSumCellID @"TKYProgressSumCell"
#define KTaskSumCellID @"TKYTaskSumCell"
@interface TKYHomePageController ()<SDCycleScrollViewDelegate,TitleViewSelectedDelegate,UITableViewDelegate,UITableViewDataSource>

/**
 概况的view
 */
@property (nonatomic, strong)TKYSurveyView *surveyView;
/**
 轮播视图
 */
@property (nonatomic, strong)SDCycleScrollView *cycleScrollView;

@property (nonatomic, strong)UIView *headerView;


/**
 进度质量安全,按钮
 */
@property (nonatomic, strong) TKYTitleView *titleView;

@property (nonatomic, strong)BaseTabelView *tableV;

/**
 悬浮按钮的view
 */
@property (nonatomic, strong)WMDragView *dragView;

/**站房信息 */
@property (nonatomic, strong)TKYProjectInfoModel *projectInfoModel;

/** 通知信息数据*/
@property (nonatomic, strong) NSArray <TKYMessageListModel *>*messageListArr;
@property (nonatomic, assign)BOOL isMessageBadge;



@property (nonatomic, strong)NSString *ss;


@end

@implementation TKYHomePageController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //获取消息列表信息
    [self requestMessageInfoList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置界面
    [self setupUI];
    //获取站房信息
    [self requestProjectInfo:@"1"];
}

/**
 设置界面
 */
- (void)setupUI{
    self.navigationItem.title = @"首页";
    self.navigationController.navigationBar.barTintColor = KNavColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:19.0]}];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav"] style:UIBarButtonItemStylePlain target:self action:@selector(changeStationHouseBarButtonItem:)];
    
    //导航右侧的消息按钮
    UIButton *rightBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBarButton setImage:[UIImage imageNamed:@"message"] forState:UIControlStateNormal];
    rightBarButton.frame = CGRectMake(0, 0, 40, 40);
    [rightBarButton addTarget:self action:@selector(messageCerterAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBarButton];
    // 1.2 右边
    [self.navigationItem.rightBarButtonItem pp_addBadgeWithText:nil];
    [self.navigationItem.rightBarButtonItem pp_moveBadgeWithX:0 Y:6];
    [self.navigationItem.rightBarButtonItem pp_setBadgeFlexMode:PPBadgeViewFlexModeHead];
//    [self.navigationItem.rightBarButtonItem pp_setBadgeLabelAttributes:^(PPBadgeLabel *badgeLabel) {
//        badgeLabel.backgroundColor = [UIColor redColor];
//        //badgeLabel.font =  [UIFont systemFontOfSize:13];
//        //badgeLabel.textColor = [UIColor blueColor];
//    }];
    //隐藏消息按钮的小红点
   // [self.navigationItem.rightBarButtonItem pp_hiddenBadge ];
    [self.headerView addSubview:self.surveyView];
    [self.headerView addSubview:self.titleView];
    [self.view addSubview:self.tableV];
    self.tableV.tableHeaderView = self.headerView;
    [self.view addSubview:self.dragView];
}

/**消息通知的数据*/
- (void)requestMessageInfoList{
    NSString *url = [NSString stringWithFormat:@"%@%@token=%@&projectId=%@&userId=%@",kApiBaseUrl, KGetMessageInfoUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],[[NSUserDefaults standardUserDefaults]objectForKey:KStationHouseID],[[NSUserDefaults standardUserDefaults]objectForKey:kUserID]];
    [KHttpRequestTool GET:url parameters:nil success:^(id response) {
        if ([response[@"code"] integerValue] == 0) {
            self.messageListArr = [TKYMessageListModel  mj_objectArrayWithKeyValuesArray:response[@"messageList"]];
         
            for (TKYMessageListModel *messageListModel in self.messageListArr) {
               // messageListModel.status = 1;
                if (messageListModel.status == 0) {
                    self.isMessageBadge = YES;
                    [self.navigationItem.rightBarButtonItem pp_showBadge ];
                }else{
                    self.isMessageBadge = NO;
                    [self.navigationItem.rightBarButtonItem pp_hiddenBadge];
                }
            }
        }else{
            [SVProgressHUD showErrorWithStatus:response[@"msg"]];
        }
    } failure:^(NSError *error) {
        
        
    }];
}

#pragma mark-- 获取站房信息
- (void)requestProjectInfo:(NSString *)ids{
    NSString *url = [NSString stringWithFormat:@"%@%@token=%@&id=%@&userId=%@ ",kApiBaseUrl, kGetProjectInfoUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],ids,[[NSUserDefaults standardUserDefaults]objectForKey:kUserID]];
    NSString *urlString = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [KHttpRequestTool GET:urlString parameters:nil success:^(id response) {
        if ([response[@"code"] integerValue] == 0) {
            self.projectInfoModel = [TKYProjectInfoModel  mj_objectWithKeyValues:response[@"projectInfoEntity"]];
            //保存站房id
            [[NSUserDefaults standardUserDefaults] setObject:self.projectInfoModel.ID forKey:KStationHouseID];
            [[NSUserDefaults standardUserDefaults] synchronize];
            _surveyView.projectInfo = self.projectInfoModel;
            //单例类保存当前项目信息
          TKYProjectInfoModel *projectInfoModel= [TKYProjectInfoModel sharedProjectInfoModel];
            projectInfoModel.projectName = self.projectInfoModel.projectName;
            projectInfoModel.ID = self.projectInfoModel.ID;
            projectInfoModel.endDateStr = self.projectInfoModel.endDateStr;
            projectInfoModel.startDateStr = self.projectInfoModel.startDateStr;

            [self requestGetCountByProjectIdAndSafeQualityFlag:self.projectInfoModel];
        }else{
            [SVProgressHUD showErrorWithStatus:response[@"msg"]];
        }
        //[self.tableV reloadData];
    } failure:^(NSError *error) {
        
        
    }];
}

//根据站房Id及质量安全标记统计不同处理状态问题数量
- (void)requestGetCountByProjectIdAndSafeQualityFlag:(TKYProjectInfoModel *)projectInfo{
    NSString *url = [NSString stringWithFormat:@"%@%@token=%@&projectId=%@&safeQualityFlag=1&startDate=%@&endDate=%@",kApiBaseUrl, kGetCountByProjectIdAndSafeQualityFlagUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],projectInfo.ID,projectInfo.startDateStr,projectInfo.endDateStr];
    [KHttpRequestTool GET:url parameters:nil success:^(id response) {
        if ([response[@"code"] integerValue] == 0) {
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"请求失败"];
        }
        [self.tableV reloadData];
        
    } failure:^(NSError *error) {
        
        
    }];
}


#pragma mark-- 按钮的点击事件
//切换站点
- (void)changeStationHouseBarButtonItem:(UIBarButtonItem *)barButtonItem{
    TKYChangeStationHouseController *vc = [[TKYChangeStationHouseController alloc] init];
    vc.changeStationHouseBlock = ^(TKYProjectInfoModel *stationHouse) {
        
        self.ss = stationHouse.projectName;
        
        [self requestProjectInfo: stationHouse.ID];
    };
    vc.drawerType = DrawerTypeMaskLeft;
    // [self cw_pushViewController:vc drewerHiddenDuration:0.01];
    [self cw_showDrawerViewController:vc animationType:CWDrawerAnimationTypeMask configuration:nil];
}

//切换消息界面
- (void)messageCerterAction:(UIBarButtonItem *)barButtonItem{
   TKYMessageCenterController *messageCenterVC = [TKYMessageCenterController new];
   messageCenterVC.messageListArr = self.messageListArr;
    messageCenterVC.isMessageBadge = self.isMessageBadge;
    [self.navigationController pushViewController:messageCenterVC animated:YES];
}

#pragma mark-- UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return 11;
    }
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 15;
    }
    return kHeightScale *170;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 120;
    }
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    // 复用
    if (section == 1) {
        TKYHomePageHeaderView *headerView = [[TKYHomePageHeaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kHeightScale*40)];
        headerView.backgroundColor = [UIColor whiteColor];
        __weak typeof(headerView) weakHeaderView = headerView;
        //开始时间
        headerView.startDateView.dateLabel.text =  self.projectInfoModel.startDateStr;
        headerView.startDateView.selectedDateBtnBlock = ^(UIButton *btn) {
            [BRDatePickerView showDatePickerWithTitle:@"请选择起始日期" dateType:BRDatePickerModeYMD defaultSelValue:@"" resultBlock:^(NSString *selectValue) {
                weakHeaderView.startDateView.dateLabel.text = selectValue;
                }];
        };
        
         //结束时间
        headerView.endDateView.dateLabel.text =  self.projectInfoModel.endDateStr;
        headerView.endDateView.selectedDateBtnBlock = ^(UIButton *btn) {
            [BRDatePickerView showDatePickerWithTitle:@"请选择结束日期" dateType:BRDatePickerModeYMD defaultSelValue:@"" resultBlock:^(NSString *selectValue) {
                weakHeaderView.endDateView.dateLabel.text = selectValue;
            }];
        };
        
        //升序
        headerView.ascendingButtonBlock = ^(UIButton *btn) {
#warning 升序
        };
        
        //降序
        headerView.descendinButtonBlock = ^(UIButton *btn) {
   #warning 降序
        };
        
        //质量
        headerView.qualityButtonBlock = ^(UIButton *button) {
            
            
    #warning 质量
        };
        //安全
        headerView.safetyButtonBlock = ^(UIButton *button) {
    #warning 安全
            
        };

        return headerView;
    }
    return nil;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        TKYProgressSumCell *cell = [tableView dequeueReusableCellWithIdentifier:kProgressSumCellID];
        
        return cell;
    }else{
        TKYTaskSumCell *cell = [tableView dequeueReusableCellWithIdentifier:KTaskSumCellID];
        if (indexPath.row == 0) {
            cell.titleLabel.textColor = kRGBColor(51, 51, 51, 1);
        }else{
            cell.titleLabel.textColor = kRGBColor(42, 42, 42, 1);;
        }
        return cell;
    }
}

#pragma mark-- TitleViewSelectedDelegate
- (void)tky_titleViewDidSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        TKYSafetyController * safetysVC = [[TKYSafetyController alloc]init];
      
        [self.navigationController pushViewController:safetysVC animated:YES];
       // NSLog(@"点击了进度");
    }else if(indexPath.row == 1){
        //  NSLog(@"点击了质量");
        TKYQualityController * qualityVC = [[TKYQualityController alloc]init];
        [self.navigationController pushViewController:qualityVC animated:YES];
    }else{
        //NSLog(@"点击进度");
        TKYProgressCountController * progressCountVC = [[TKYProgressCountController alloc]init];
        [self.navigationController pushViewController:progressCountVC animated:YES];
    }
}

- (TKYSurveyView *)surveyView{
    if (_surveyView == nil) {
        _surveyView = [[TKYSurveyView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kHeightScale *130)];
    }
    return _surveyView;
}

//显示安全, 质量, 进度的view
- (TKYTitleView *)titleView{
    if (_titleView == nil) {
        _titleView = [[TKYTitleView alloc]initWithFrame:CGRectMake(0, self.surveyView.kx_bottom, kScreenWidth, kHeightScale *85)];
       // _titleView.backgroundColor = [UIColor redColor];
        _titleView.delegate = self;
    }
    return _titleView;
}

//
- (BaseTabelView *)tableV{
    if (_tableV == nil) {
        _tableV = [[BaseTabelView alloc]initWithFrame:CGRectMake(0, MyNavBarHeight, kScreenWidth, kScreenHeight- MyNavBarHeight) style:UITableViewStyleGrouped];
        _tableV.dataSource = self;
        _tableV.delegate = self;
        _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableV registerNib:[UINib nibWithNibName:@"TKYProgressSumCell" bundle:nil]  forCellReuseIdentifier:kProgressSumCellID];
        [_tableV registerClass:[TKYTaskSumCell class] forCellReuseIdentifier:KTaskSumCellID];
    }
    return _tableV;
}

// 放置轮播图,安全, 质量, 进度view的headerView
- (UIView *)headerView{
    if (_headerView == nil) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, MyNavBarHeight, kScreenWidth, self.surveyView.kx_height + self.titleView.kx_height)];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    return _headerView;
}

//悬浮按钮的view
- (WMDragView *)dragView{
    if (_dragView == nil) {
        _dragView = [[WMDragView alloc]initWithFrame:CGRectMake(kScreenWidth - kWidthScale*68, kScreenHeight - TabbarHeight - kWidthScale * 68, kWidthScale * 68, kWidthScale *68)];
        _dragView.backgroundColor = [UIColor clearColor];
        //[_dragView tky_cornerWithRadius:kWidthScale *34 borderColor:nil borderWidth:0];
//        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(0, self.dragView.kx_height/2- kWidthScale *10, kWidthScale * 50, kWidthScale *20)];
//        lab.text = @"BIM";
//        lab.textAlignment = NSTextAlignmentCenter;
//        lab.textColor = [UIColor whiteColor];
//        [_dragView addSubview:lab];
        _dragView.imageView.image = [UIImage imageNamed:@"bim"];
        //点击了悬浮按钮
        __weak typeof(self) weakSelf = self;
        _dragView.clickDragViewBlock = ^(WMDragView *dragView) {
            TKYBimModelController *bimModelVC = [[TKYBimModelController alloc]init];
            [weakSelf.navigationController pushViewController:bimModelVC animated:YES];
            NSLog(@"点击了悬浮按钮");
        };
    }
    return _dragView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
